package com.web.controller;

import com.alibaba.fastjson.JSON;
import com.web.entity.ResponseResult;
import com.web.entity.Student;
import com.web.service.StudentService;
import com.web.service.impl.StudentServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/findStudentByKeyword")
public class FindStudentByKeywordServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求和响应编码
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        // 设置响应类型
        resp.setContentType("application/json;charset=UTF-8");

        // 获取请求参数
        String keyword = req.getParameter("keyword");

        if (keyword == null || keyword.isEmpty()) {
            resp.getWriter().write(JSON.toJSONString(new ResponseResult(400, "关键字不能为空", null)));
            return;
        }

        StudentService studentService = new StudentServiceImpl();
        List<Student> students = studentService.findStudentkeyword(keyword);

        if (students.isEmpty()) {
            resp.getWriter().write(JSON.toJSONString(new ResponseResult(404, "未找到相关学生", null)));
        } else {
            resp.getWriter().write(JSON.toJSONString(new ResponseResult(200, "OK", students)));
        }
    }
}
